﻿using System;
using System.Text;

namespace Codebook.Extensions
{
    public static class StringExtensions
    {
        public static string LeftTo(this string str, int fromPosition, int toPosition)
        {
            int startIndex = fromPosition - 1;
            int length = toPosition - fromPosition + 1;

            return LeftIndex(str, startIndex, length);
        }

        public static string LeftTo(this string str, int toPosition)
        {
            return LeftTo(str, 1, toPosition);
        }

        public static string RightTo(this string str, int fromPosition, int toPosition)
        {
            str = Reverse(str);
            str = LeftTo(str, fromPosition, toPosition);

            return Reverse(str);
        }

        public static string RightTo(this string str, int toPosition)
        {
            return RightTo(str, 1, toPosition);
        }

        public static string TheLeft(this string str, int position)
        {
            return LeftTo(str, position, position);
        }

        public static string TheRight(this string str, int position)
        {
            return RightTo(str, position, position);
        }

        public static string Unite(this string[] strArray, params char[] separator)
        {
            var strBuilder = new StringBuilder();
            foreach (string str in strArray) {
                strBuilder.Append(str).Append(separator);
            }

            var builderLength = strBuilder.Length;
            if (builderLength > 0) {
                strBuilder.Remove(builderLength - 1, 1);
            }

            return strBuilder.ToString();
        }

        private static string LeftIndex(string value, int fromIndex, int length)
        {
            if (string.IsNullOrEmpty(value)) return string.Empty;
            else value = value.Trim();

            if (fromIndex < 0) fromIndex = 0;
            if (fromIndex >= value.Length) return string.Empty;

            if (length <= 0) return string.Empty;
            if (fromIndex + length > value.Length)
                length = value.Length - fromIndex;

            value = value.Substring(fromIndex, length);
            return value;
        }

        private static string Reverse(string value)
        {
            if (string.IsNullOrEmpty(value)) return string.Empty;

            char[] arrayValue = value.ToCharArray();
            Array.Reverse(arrayValue);

            return new string(arrayValue);
        }

    }
}
